import React, { useState, useEffect } from 'react';
import {
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  message,
  Card,
  Tag,
  Popconfirm,
  Upload,
  Tree,
  Row,
  Col,
  Alert,
  Divider
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  FolderOutlined,
  FileOutlined,
  UploadOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import { categoryAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { Option } = Select;
const { TextArea } = Input;

const AdminCategories = () => {
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState(null);
  const [categoryForm] = Form.useForm();
  const [expandedKeys, setExpandedKeys] = useState([]);
  const { hasAdminPermission } = useAdminAuth();
  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadCategories();
  }, []);

  const loadCategories = async () => {
    setLoading(true);
    try {
      const response = await categoryAPI.getCategories();
      if (response.success) {
        setCategories(response.data);
        setTreeData(buildTreeData(response.data));
        // 默认展开第一级
        const firstLevelKeys = response.data
          .filter(cat => !cat.parentId)
          .map(cat => cat.id.toString());
        setExpandedKeys(firstLevelKeys);
      }
    } catch (error) {
      message.error('加载分类列表失败');
    } finally {
      setLoading(false);
    }
  };

  const buildTreeData = (data, parentId = null, level = 0) => {
    return data
      .filter(item => item.parentId === parentId)
      .map(item => {
        const isSecondLevel = level === 1;
        const children = level < 1 ? buildTreeData(data, item.id, level + 1) : [];
        
        return {
          title: (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
              <span>
                {item.icon && <span style={{ marginRight: 8 }}>{item.icon}</span>}
                {item.name}
                <Tag color={item.status === 'active' ? 'green' : 'red'} style={{ marginLeft: 8 }}>
                  {item.status === 'active' ? '启用' : '禁用'}
                </Tag>
                <Tag color="blue" style={{ marginLeft: 4 }}>
                  {item.productCount || 0} 个商品
                </Tag>
                {level === 0 && <Tag color="purple" style={{ marginLeft: 4 }}>一级分类</Tag>}
                {level === 1 && <Tag color="orange" style={{ marginLeft: 4 }}>二级分类</Tag>}
              </span>
              <Space size="small" onClick={e => e.stopPropagation()}>
                {!isSecondLevel && (
                  <Button
                    type="link"
                    size="small"
                    icon={<PlusOutlined />}
                    onClick={() => handleAdd(item.id)}
                    style={buttonStyle}
                  >
                    添加子分类
                  </Button>
                )}
                <Button
                  type="link"
                  size="small"
                  icon={<EditOutlined />}
                  onClick={() => handleEdit(item)}
                  style={buttonStyle}
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个分类吗？"
                  description="删除后该分类下的商品将移至未分类"
                  onConfirm={() => handleDelete(item.id)}
                >
                  <Button
                    type="link"
                    danger
                    size="small"
                    icon={<DeleteOutlined />}
                    style={buttonStyle}
                  >
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            </div>
          ),
          key: item.id.toString(),
          icon: item.parentId ? <FileOutlined /> : <FolderOutlined />,
          children: children
        };
      });
  };

  const handleAdd = (parentId = null) => {
    // 检查层级限制
    if (parentId) {
      const parentCategory = categories.find(c => c.id === parentId);
      if (parentCategory && parentCategory.parentId) {
        message.error('最多只能创建二级分类');
        return;
      }
    }
    
    setEditingCategory(null);
    categoryForm.resetFields();
    categoryForm.setFieldsValue({
      parentId: parentId,
      status: 'active',
      sort: 0
    });
    setModalVisible(true);
  };

  const handleEdit = (category) => {
    setEditingCategory(category);
    categoryForm.setFieldsValue(category);
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await categoryAPI.deleteCategory(id);
      if (response.success) {
        message.success('删除成功');
        loadCategories();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await categoryForm.validateFields();
      
      // 再次检查层级限制
      if (values.parentId) {
        const parentCategory = categories.find(c => c.id === values.parentId);
        if (parentCategory && parentCategory.parentId) {
          message.error('最多只能创建二级分类');
          return;
        }
      }
      
      let response;
      if (editingCategory) {
        response = await categoryAPI.updateCategory(editingCategory.id, values);
      } else {
        response = await categoryAPI.addCategory(values);
      }

      if (response.success) {
        message.success(editingCategory ? '更新成功' : '添加成功');
        setModalVisible(false);
        loadCategories();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  const getParentOptions = (currentId = null) => {
    const options = [{ value: null, label: '无（作为一级分类）' }];
    
    // 只显示一级分类作为父级选项
    const firstLevelCategories = categories.filter(cat => !cat.parentId);
    
    firstLevelCategories.forEach(item => {
      if (item.id !== currentId) {
        options.push({
          value: item.id,
          label: item.name
        });
      }
    });
    
    return options;
  };

  // 统计信息
  const getStatistics = () => {
    const firstLevel = categories.filter(cat => !cat.parentId);
    const secondLevel = categories.filter(cat => cat.parentId);
    const totalProducts = categories.reduce((sum, cat) => sum + (cat.productCount || 0), 0);
    
    return { firstLevel: firstLevel.length, secondLevel: secondLevel.length, totalProducts };
  };

  const stats = getStatistics();

  return (
    <div>
      {/* 页面标题 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <AppstoreOutlined style={{ fontSize: '24px', color: '#1890ff', marginRight: 12 }} />
            <div>
              <h2 style={{ margin: 0, fontSize: '20px', fontWeight: 600 }}>商品分类管理</h2>
              <p style={{ margin: '4px 0 0 0', color: '#666', fontSize: '14px' }}>
                管理商品分类层级结构，当前共有 {stats.firstLevel} 个一级分类，{stats.secondLevel} 个二级分类
              </p>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ textAlign: 'center', padding: '8px 16px', background: '#f5f5f5', borderRadius: '6px' }}>
              <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#1890ff' }}>{stats.totalProducts}</div>
              <div style={{ fontSize: '12px', color: '#666' }}>总商品数</div>
            </div>
            {hasAdminPermission('category:add') && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleAdd()}
                style={{ ...buttonStyle, height: '40px', fontSize: '15px' }}
                size="large"
              >
                添加一级分类
              </Button>
            )}
          </div>
        </div>
      </Card>

      {/* 说明和操作区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Alert
          message="分类层级说明"
          description={
            <div>
              <p style={{ margin: '8px 0' }}>
                • 本系统最多支持二级分类结构，即：<Tag color="purple">一级分类</Tag> → <Tag color="orange">二级分类</Tag>
              </p>
              <p style={{ margin: '8px 0' }}>
                • 删除分类时请确保该分类下无商品和子分类
              </p>
              <p style={{ margin: '8px 0 0 0' }}>
                • 可以在分类树中直接进行编辑、删除和添加子分类操作
              </p>
            </div>
          }
          type="info"
          showIcon
        />
      </Card>

      {/* 分类树形结构 */}
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>
              <FolderOutlined style={{ marginRight: 8 }} />
              分类树形结构
            </span>
            <div style={{ fontSize: '12px', color: '#666' }}>
              点击展开/收起分类，鼠标悬停查看操作按钮
            </div>
          </div>
        }
        loading={loading}
      >
        {categories.length === 0 ? (
          <div style={{ 
            textAlign: 'center', 
            padding: '80px 0',
            background: '#fafafa',
            borderRadius: '8px',
            border: '2px dashed #d9d9d9'
          }}>
            <AppstoreOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: 16 }} />
            <div style={{ fontSize: '16px', color: '#999', marginBottom: 16 }}>
              暂无分类数据
            </div>
            {hasAdminPermission('category:add') && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleAdd()}
                style={buttonStyle}
              >
                立即添加第一个分类
              </Button>
            )}
          </div>
        ) : (
          <div style={{ minHeight: '400px' }}>
            <Tree
              showIcon
              blockNode
              expandedKeys={expandedKeys}
              onExpand={setExpandedKeys}
              treeData={treeData}
              style={{ fontSize: '14px' }}
            />
          </div>
        )}
      </Card>

      {/* 添加/编辑分类模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <AppstoreOutlined style={{ marginRight: 8 }} />
            {editingCategory ? '编辑分类' : '添加分类'}
          </div>
        }
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form
          form={categoryForm}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="parentId"
            label="父级分类"
            help="只能创建一级分类和二级分类，最多两级"
          >
            <Select
              placeholder="请选择父级分类"
              options={getParentOptions(editingCategory?.id)}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="icon"
                label="分类图标"
              >
                <Input 
                  placeholder="请输入图标（如：🏠）" 
                  addonAfter={
                    <Upload
                      showUploadList={false}
                      beforeUpload={() => false}
                    >
                      <Button size="small" icon={<UploadOutlined />} style={buttonStyle}>
                        上传
                      </Button>
                    </Upload>
                  }
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="sort"
                label="排序"
                rules={[{ required: true, message: '请输入排序' }]}
              >
                <InputNumber
                  min={0}
                  style={{ width: '100%' }}
                  placeholder="数字越小越靠前"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="分类描述"
          >
            <TextArea
              rows={3}
              placeholder="请输入分类描述"
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminCategories; 